$(function() {

	'use strict';

	var remote = {

		_URL_ROOT : 'http://h5.xinwen4.com/web/score/',

		_fakeAjax: function() {},

		_doAjax: function(op, data, success) {
			$.ajax({
				url      : this._URL_ROOT + op,
				dataType : 'jsonp',
				data     : data,
				success  : function(resp) {
					success && success(resp);
				}
			});
		},

		fetchKey: function(success) {
			return this._doAjax('init', null, success);
		},

		uploadScore: function(score, userCode, success) {
			return this._doAjax('upload_score', {
				userCode : userCode,
				score    : score
			}, success);
		}
	};

	var userCode = localStorage.getItem('userCode');

	if (!userCode) {
		remote.fetchKey(function(resp) {
			userCode = resp.info;
			localStorage.setItem('userCode', userCode);
		});
	}

	var shareSDK = {

        _info : null,

        set: function(info) {

            info || (info = this._info);

            info.fTitle || (info.fTitle = this._info.fTitle);
            info.fDesc  || (info.fDesc  = this._info.fDesc);
            info.tTitle || (info.tTitle = this._info.tTitle);
            info.image  || (info.image  = this._info.image);
            info.link   || (info.link   = this._info.link);
            info.onDone || (info.onDone = this._info.onDone);

            window.wx && wx.ready(function() {

                wx.onMenuShareAppMessage({
                    title   : info.fTitle,
                    desc    : info.fDesc,
                    link    : info.link,
                    imgUrl  : info.image,
                    success : function() {
                        info.onDone && info.onDone();
                    }
                });

                wx.onMenuShareTimeline({
                    title   : info.tTitle,
                    link    : info.link,
                    imgUrl  : info.image,
                    success : function() {
                        info.onDone && info.onDone();
                    }
                });

            });

            return this;
        },

        init: function(info) {

            var that = this;

            if (window.wx_config) {

                window.wx_config.jsApiList = [
                    'onMenuShareTimeline',
                    'onMenuShareAppMessage'
                ];

                wx.config(window.wx_config);
            }

            this._info = info;
            this.set();

            return this;
        }

    }.init({
        fTitle : '穿越时空，马可•波罗来广州啦！',
        fDesc  : '快来助跑马可•波罗，帮他实现广州之旅的梦想吧~',
        tTitle : '我帮马可•波罗助跑0千米，超越0%的网友，还差一点点就到广州啦！',
        image  : 'http://www.huihaicenter.com/www/projects/mcppp/images/shareit.jpeg',
        link   : window.location.href,
        onDone : $.noop
    });

	function updateShare(score, rank) {
		shareSDK.set({
			tTitle : '我帮马可•波罗助跑' + score + '千米，超越' + rank + '%的网友，还差一点点就到广州啦！'
		});
	}

	// 动画元素类
	function AniItem(el) {

		this._el        = el;
		this._diffX     = el.data('x')         ? +el.data('x')         : 0;
		this._diffY     = el.data('y')         ? +el.data('y')         : 0;
		this._fromScale = el.data('fromscale') ? +el.data('fromscale') : 0;
		this._toScale   = el.data('toscale')   ? +el.data('toscale')   : 1;
		this._duration  = el.data('duration')  ? +el.data('duration')  : 0;
		this._delay     = el.data('delay')     ? +el.data('delay')     : 0;
		this._targetPct = el.data('pct')       ? +el.data('pct') 	   : 0.999;
	}
	AniItem.prototype = {

		_POS_FIX : window.htmlFontSize_,

		_calcPct: function(diffTime) {
			return (diffTime - this._delay) > 0 ?
					(diffTime - this._delay) / this._duration : 0;
		},

		_render: function(pct) {

			if (pct > this._targetPct) {
				this._el.addClass('done');

			} else {

				var info = {
					x : this._diffX * pct * this._POS_FIX,
					y : this._diffY * pct * this._POS_FIX,
					s : this._fromScale + (this._toScale - this._fromScale) * pct
				};

				this._el.removeClass('done').attr('style', '-webkit-transition:all 0.2s;-webkit-transform: ' +
						'scale(' + info.s + ') ' +
						'translate3d(' + info.x + 'px, ' + info.y + 'px, 0)');
			}

			return this;
		},

		update: function(diffTime) {
			return this._render(this._calcPct(diffTime));
		}
	};

	// 距离显示对象
	var gameInfo = {

		_boxEls     : $('.page2 .info-box'),
		_distanceEl : $('.page2 .info-distance em'),
		_timeEl     : $('.page2 .info-time em'),

		setDistance: function(dist) {
			this._distanceEl.html(dist);
			return this;
		},

		setTimeLeft: function(time) {
			this._timeEl.html(time);
			return this;
		},

		show: function() {
			this._boxEls.show();
			return this;
		},

		hide: function() {
			this._boxEls.hide();
			return this;
		}
	};

	var countDown = {

		_popEl : $('.page2 .count-down'),

		show: function(callback) {

			var that = this;

			this._popEl.show();

			setTimeout(function() {
				that._popEl.addClass('show');
			}, 50);

			setTimeout(function() {
				callback && callback();
			}, 8500);

			return this;
		},

		hide: function() {

			var that = this;

			this._popEl.removeClass('show');

			setTimeout(function() {
				that._popEl.hide();
			}, 600);

			return this;
		},

		reset: function() {
			this._popEl.removeClass('show');
			return this;
		}
	};

	// 全局时钟
	var ticker = {

		_INIT_TICK : 0,
		_TICK_STEP : 16,

		_enabled   : false,
		_tickCount : 0,
		_delta     : 1,
		_tid       : null,

		startOnce: function() {

			var that = this;

			this._enabled = true;

			this._tid && clearTimeout(this._tid);
			this._tid = setTimeout(function() {
				that._enabled = false;
			}, 200);

			return this;
		},

		setTickCbk: function(onTick) {
			this._onTick = onTick;
			return this;
		},

		reset: function() {

			var that = this;

			this._enabled   = false;
			this._tickCount = this._INIT_TICK;

			this._onTick && this._onTick(this._tickCount);

			return this;
		},

		init: function() {

			var that = this;

			this.reset();

			function tick() {

				if (that._enabled) {
					if(that._tickCount < 8500){
						that._delta = 2;
					}else if(that._tickerCount < 9500){
						that._delta = 1.5;
					}else if(that._tickerCount < 10500){
						that._delta = 1.2;
					} else {
						that._delta = 0.75;
					}
					that._tickCount += that._TICK_STEP * that._delta;
					that._onTick && that._onTick(that._tickCount);
				}

				requestAnimationFrame(tick);
			}

			tick();

			return this;
		}

	}.init();

	// 人物动画
	var role = {

		_INTERVAL   : 100,
		_CLICK_TIME : 150,

		_running   : false,
		_imgEl     : $('.page2 .person'),
		_imgSrcs   : [],
		_lastIndex : 0,
		_tid       : null,

		_doSwitch: function(index) {
			this._lastIndex = index;
			this._imgEl.attr('src', this._imgSrcs[index]);
			return this;
		},

		_playStand: function() {
			return this._doSwitch(0);
		},

		_playRun: function() {

			if (this._lastIndex === 0) {
				this._doSwitch(1);
			} else if (this._lastIndex === 1) {
				this._doSwitch(2);
			} else if (this._lastIndex === 2) {
				this._doSwitch(1);
			} else {
				this._doSwitch(0);
			}

			return this;
		},

		trigger: function() {

			var that = this;

			this._running = true;
			this._tid && clearTimeout(this._tid);
			this._tid = setTimeout(function() {
				that._running = false;
			}, this._CLICK_TIME);

			return this;
		},

		init: function() {

			var that = this;

			this._imgSrcs[0] = this._imgEl.attr('src');
			this._imgSrcs[1] = this._imgEl.data('src1');
			this._imgSrcs[2] = this._imgEl.data('src2');

			setInterval(function() {

				if (that._running) {
					that._playRun();
				} else {
					that._playStand();
				}

			}, this._INTERVAL);

			return this;
		}

	}.init();

	// 游戏控制器
	var gamePage = {

		_INIT_DISTANCE   : 10000,
		_INIT_TIME       : 15, // modify
		_DISTANCE_STEP_S : 7,
		_DISTANCE_STEP_L : 99,
		_THRESHOLD       : 0.005, // modify

		_started  : false,
		_distance : 0,

		_aniItems : [],
		_ticker   : null,

		_flashEl  : $('.page2 .time-flash'),
		_jiayouEl : $('.page2 .jiayou-tip'),
		_buffEl   : $('.page2 .buff-tip'),

		_getScore: function() {

			var score = 0, that = this;

			if (Math.random() > this._THRESHOLD) {
				score = this._DISTANCE_STEP_S;

			} else {
				score = this._DISTANCE_STEP_L;
				this._buffEl.addClass('show');
				setTimeout(function() {
					that._buffEl.removeClass('show');
				}, 2000);
			}

			return score;
		},

		_startCountDown: function(seconds, onDone, onProgress) {

			var timeLeft = seconds;

			var iid = setInterval(function() {

				if (--timeLeft > 0) {
					onProgress(timeLeft);

				} else {
					onDone();
					clearInterval(iid);
				}

			}, 1000);

			return this;
		},

		reset: function() {

			this._distance = this._INIT_DISTANCE;

			ticker.reset();
			countDown.reset();

			gameInfo.hide();
			gameInfo.setDistance(this._INIT_DISTANCE);
			gameInfo.setTimeLeft(this._INIT_TIME);

			return this;
		},

		start: function(callback) {

			var that = this;

			countDown.show(function() {
				countDown.hide();
				gameInfo.show();
				that._started = true;

				that._startCountDown(that._INIT_TIME, function() {
					that._started = false;
					that._flashEl.hide();
					that._jiayouEl.remove('show');
					gameInfo.setTimeLeft(0);
					callback && callback(that._INIT_DISTANCE - that._distance);

				}, function(timeLeft) {

					gameInfo.setTimeLeft(timeLeft);

					if (timeLeft === 4) {
						that._flashEl.show();
						that._jiayouEl.addClass('show');
					}

					if (timeLeft === that._INIT_TIME - 3) {
						// 镇海楼
					}

					if (timeLeft === 5) {
						// 小蛮腰
					}
				});
			});

			return this;
		},

		init: function() {

			var that = this;

			$('.page2 .content .anil').each(function() {
				that._aniItems.push(new AniItem($(this)));
			});

			ticker.setTickCbk(function(diffTime) {
				for (var i = that._aniItems.length; i--;) {
					that._aniItems[i].update(diffTime);
				}
			}).reset();

			$('.page2').on('touchstart', function() {

				if (that._started) {
					$('#paiAudio')[0].play();
					ticker.startOnce();
					role.trigger();
					that._distance -= that._getScore();
					gameInfo.setDistance(that._distance);
				}

				return false;
			});

			return this.reset();
		}

	}.init();

	var page = {

		switchTo: function(pageName) {
			$('.pt-page').removeClass('pt-page-current');
			$('.' + pageName).addClass('pt-page-current');
			return this;
		}
	};

	var pageEnter = {

		init: function() {

			Zepto.fn.typeWords = function (config) {

				var $this  = $(this),
					arr       = config.words.split(' '),
					arrlen    = arr.length,
					arrIndex  = 0,
					len       = 0,
					sInterval = config.sInterval || 200,
					wInterval = config.wInterval || 200;

				if (!arrlen) {
					return false;
				}

				var sentenceTimer = void 0,
					wordTimer = void 0;

				(function typeit() {
					if (arrIndex >= arrlen) {
						clearTimeout(sentenceTimer);
						config.callback && config.callback();
						return false;
					} else {
						var index = 0,
							curHtml = void 0,
							html = $this.html();

						len = arr[arrIndex].length;
						wordTimer = setInterval(function () {
							curHtml = html + arr[arrIndex].substring(0, index++);
							$this.html(curHtml);
							if (index > len) {
								clearInterval(wordTimer);
								arrIndex++;
								sentenceTimer = setTimeout(function () {
									$this.html($this.html() + '<br />');
									typeit();
								}, sInterval);
							}
						}, wInterval);
					}
				})();
			};

			Zepto('#destWord').typeWords({
				words     : '我是马可•波罗 来自意大利 700年前 我通过丝绸之路来到中国 见证了中华文明的繁荣 我一直想去广州 希望你能帮我完成愿望',
				wInterval : 100,
				sInterval : 200,
				callback  : function callback() {
					Zepto('#typeAudio')[0].pause();
					Zepto('.slideup').addClass('pt-page-moveFromBottom');
				}
			});

			Zepto('.slideup').one('touchstart', function() {
				$('#bgmAudio')[0].play();
				page.switchTo('page1');

				setTimeout(function() {
					$('.page0').remove();
				}, 2000);

				return false;
			});

			$('.page1 .btn').one('touchstart', function() {

				page.switchTo('page2');

				gamePage.reset().start(function(score) {

					pageResult.render(score);

					setTimeout(function() {
						page.switchTo('page3');
					}, 1000);
				});

				setTimeout(function() {
					$('.page1').remove();
				}, 1000);

				return false;
			});

			return this;
		}

	}.init();

	var pageResult = {

		// _rootTime : new Date(2018,3,30,0,0,0).getTime(),
		// _countPerSec : 20,
		// _countPerSec : 2,

		render: function(score) {

			// total = localStorage.getItem('ntotal') ? +localStorage.getItem('ntotal') : 0;
			// total += score;
            //
			// localStorage.setItem('ntotal', total);
            //
			// var diffCount = Math.floor((new Date().getTime() - this._rootTime) / 1000) * this._countPerSec;
			// total += diffCount;
            //
			// rank = Math.floor(score * 100 / 1100);
            //
			// if (rank >= 100) {
			// 	rank = 99;
			// } else if (rank < 5) {
			// 	rank = 5;
			// } else {
			// 	// Do nothing
			// }
            //
			// road = (total / 6440).toFixed(2);

			remote.uploadScore(score, userCode, function(resp) {

				$('.result-score span').html(score);
				$('.result-rank').html(resp.info.passPercent);
				$('.result-score-total').html(resp.info.totalScore);
				$('.result-road-count').html((resp.info.totalScore / 6440).toFixed(2));

				updateShare(score, resp.info.passPercent);
			});

			return this;
		},

		init: function() {

			var that = this;

			$('.page3 .primary-btn').click(function () {
				$('.sharemask').show();
				return false;
			});

			$('.sharemask').on('touchstart', function() {
				$('.sharemask').hide();
				return false;
			});

			$('#againGame').click(function() {

				page.switchTo('page2');

				gamePage.reset().start(function(score) {
					that.render(score);

					setTimeout(function() {
						page.switchTo('page3');
					}, 1000);
				});

				return false;
			});

			return this;
		}

	}.init();

	page.switchTo('page0');

	// $('.page0').remove();
	// $('.page0, .page1').remove();
    //
	// page.switchTo('page3');
	// pageResult.render(500);

});
